package com.apexsoft.assets.base.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

import java.util.concurrent.ScheduledFuture;

/**
 * Created on 2018/9/20.
 *
 * @author Sury
 */
public class TaskSchedulerUtils {
    private static final Logger LOG = LoggerFactory.getLogger(TaskSchedulerUtils.class);
    private static ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    static {
        taskScheduler.setPoolSize(10);
        //必须得先初始化，才能使用
        taskScheduler.initialize();
    }
    public static String getCronExpression(int seconds){
        int sec = seconds%60;
        int min = seconds/60;
        StringBuffer cornBuf = new StringBuffer();
        cornBuf.append("0");
        if(sec>0){
            cornBuf.append("/").append(sec);
        }
        cornBuf.append(" ");
        if(min>0){
            cornBuf.append("0/").append(min);
        }else{
            cornBuf.append("*");
        }
        cornBuf.append(" ");
        cornBuf.append("* * * ?");
        return cornBuf.toString();
    }
    public static ThreadPoolTaskScheduler getTaskScheduler(){
        return taskScheduler;
    }

    public static ScheduledFuture<?> schedule(Runnable task, Trigger trigger){
        try{
            return taskScheduler.schedule(task,trigger);
        }catch (Exception ex){
            LOG.error("设置定时任务失败",ex);
            return null;
        }
    }

    public static ScheduledFuture<?> schedule(Runnable task, int seconds){
        try{
            return taskScheduler.schedule(task,new CronTrigger(getCronExpression(seconds)));
        }catch (Exception ex){
            LOG.error("设置定时任务失败",ex);
            return null;
        }
    }

    public static void execute(Runnable task){
        try{
            taskScheduler.execute(task);
        }catch (Exception ex){
            LOG.error("执行任务失败",ex);
        }
    }

    public static void shutdown(){
        taskScheduler.shutdown();
    }
}
